/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servermonitor;

/**
 *
 * @author otaviokz
 */
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.Semaphore;

public class ServerThread implements Runnable {

    private ObjectOutputStream output;
    private ObjectInputStream input;
    private Socket connection;
    private String clientName;
    private Semaphore left, right, chairs;

    public ServerThread(Socket conn, String cliName, Semaphore l, Semaphore r, Semaphore chairs) {
        this.connection = conn;
        this.clientName = cliName;
        this.chairs = chairs;
        this.left = l;
        this.right = r;
    }

    public void run() {
        try {
            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush();
            input = new ObjectInputStream(connection.getInputStream());

            while (true) {
                //process the connection
                String inMsg = (String) input.readObject();
                String outMsg = "";

                if (inMsg.equalsIgnoreCase("Who am I?")) {
                    outMsg = "Success. You are: " + clientName;
                } else if (inMsg.equalsIgnoreCase("P(chair)")) {
                    chairs.acquire();
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("P(left)")) {
                    left.acquire();
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("P(right)")) {
                    right.acquire();
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("V(left)")) {
                    left.release();
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("V(right)")) {
                    right.release();
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("V(chair)")) {
                    chairs.release();
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("Eating")) {
                    System.out.println(String.format("%s eating", clientName));
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("Thinking")) {
                    System.out.println(String.format("%s thinking", clientName));
                    outMsg = "Success";
                } else if (inMsg.equalsIgnoreCase("Hungry")) {
                    System.out.println(String.format("%s hungry", clientName));
                    outMsg = "Success";
                } else {
                    connection.close();
                }

                //reply to client
                output.writeObject(outMsg);

                output.flush();
            }

        } catch (Exception ex) {
            System.out.println("ERROR: " + ex.getMessage());

        }
    }
}
